/* When the document is loaded and ready, initialize */
$(document).ready(initialize);

/* Gets station list and hides loader images*/
function initialize()
{
  station_getStationList();

  $("#loader_prtCommand").hide();
  $("#loader_selectStation").hide();
  $("#loader_addPassenger").hide();
  $("#loader_getDistributions").hide();
  $("#loader_stationConfig").hide();
}

/* Gets station list */
function station_getStationList()
{
  $.getJSON("php/Stations.php", function(jsonData)
  {
    $.each(jsonData, function(key,value)
    {
      $('#station_selectedStation').append($("<option></option>").attr("value",value).text('İstasyon ' + value));
    });
  });
}

/* When a station is selected, get information about that station */
function station_getStation(sta)
{
  $('#station_noOfPassengers, #station_infoOfPassengers, #station_distType, #station_distParams').empty();
  $('#station_passengerIcons').empty();

  $("#loader_selectStation").show()

  var stationId = sta.value;

  $.getJSON('php/Stations.php/'+ stationId, function(result)
  {
    var stationInfo = result[0];
    var passengerIds = result[1];

    $("#station_noOfPassengers").append("<strong>Yolcu Sayısı: </strong>" + stationInfo.numberOfPassenger);

    var i = 0;
    $.each(passengerIds, function()
    {
      var pas_icon = document.createElement("a");

      pas_icon.className ="icon-user";
      pas_icon.id = (passengerIds[i]);
      pas_icon.setAttribute('href', '#');
      pas_icon.setAttribute('rel', 'popover');
      
      document.getElementById('station_passengerIcons').appendChild(pas_icon);
      document.getElementById('station_passengerIcons').appendChild(document.createTextNode(" "));

      i++;
    });

    station_bindPopups();
    $("#loader_selectStation").delay(200).fadeOut('fast');

    station_plot();
  });
}

/* Binds passenger icon to its details popup */
function station_bindPopups()
{
  $("a[rel=popover]").each(function()
  {
    station_showPassenger($(this).attr('id'));
  });
}

/* Shows passenger information in a popup */
var v='';
function station_showPassenger(id)
{
  var id_num=id;
  console.log("id: " + id);
  console.log("id_num: " + id_num);
  $.getJSON('php/Passengers.php/'+id_num, function(passenger)
  {
    console.log("passenger: " + passenger );
    v='';
    $.each(passenger, function(pas_key, pas_value)
    {
      v+=" "+pas_key+" "+pas_value+" ";
    });

    $("#"+id).popover(
    {
      trigger: 'hover',
      placement: 'top',
      html: true,
      title:"Passenger "+ id_num,
      content: " " + v
    })
    .click(function(e)
    {
      e.preventDefault();
    });
  });

  console.log("v: " + v);
  return v;
}

/* Adds passengers to the selected station */
function station_addPassenger()
{
  var stationId = document.getElementById('station_selectedStation').value;
  var num = document.getElementById('station_passengerNumberToAdd').value;

  if(stationId != "")
  {
    alert(stationId + " numaralı istasyona " + num + " yolcu ekleniyor...");

    var sent = $.ajax(
    {
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "http://" + HOST_URL + ":85/" + stationId + "/" + "web_addPassenger" + "/" + num,
      beforeSend:function ()
      {
        $("#loader_addPassenger").show();
      },
      complete: function ()
      {
        $("#loader_addPassenger").hide();
      },
      success: function(data)
      {
        alert(data);
        alert("Başarılı!");
      },
      error: function()
      {
        alert("Başarısız!");
      }
    });
  }
}

/* Gets the distribution parameters from json file */
var distNameAndParameters;
function station_getDistributions(sel) 
{
  $("#loader_getDistributions").show();
  $.getJSON('json/Dist.json', function(json){

  var $container = $('#station_parameters').empty();
  distNameAndParameters=null;
  $.each(json.distributions, function(i, distribution) 
  {
    if(distribution.type==sel.value) 
    {
      $.each(distribution.parameters, function(j, parameters) 
      {
        //This is for creating a new div tag
        var divTag = document.createElement("div");
        divTag.id = "div1";
        divTag.setAttribute("align","center");

        //divTag.style.border = "1px solid #ccc";
        divTag.innerHTML = distribution.name + " Dağılım Parametreleri";
        //$('<br/>').insertBefore($('#div1'));
        document.getElementById("station_parameters").appendChild(divTag);
        distNameAndParameters=distribution.name;
        $.each(parameters, function(parameter_key, parameter_value) 
        {
          //This for creating a new textbox
          var label, textbox;
          label = document.createElement('label');
          label.appendChild(document.createTextNode(parameter_key+" "));
          textbox = document.createElement('input');
          textbox.className= "span12";
          textbox.type = 'text';
          textbox.value=parameter_value;
          label.appendChild(textbox);
          document.getElementById('station_parameters').appendChild(label);  
          $container.append('<hr />');
          distNameAndParameters+=" "+parameter_key+":"+parameter_value;
        });
      });
    }
  });
  $("#loader_getDistributions").delay(200).fadeOut('fast');
  });
}

/* Sends the defined distribution parameters to the server */
function station_config()
{
  var stationId = document.getElementById('station_selectedStation').value;
  var selectedDistribution = document.getElementById('station_selectedDistribution').value;

  if(selectedDistribution != "")
  {
    var sent = $.ajax(
    {
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "http://" + HOST_URL + ":85/"+stationId+"/"+"web_config"+"/"+distNameAndParameters,
      beforeSend:function ()
      {
        $("#loader_stationConfig").show();
      },
      complete: function ()
      {
        $("#loader_stationConfig").hide();
      },
      success: function(data)
      {
        alert(data);
        alert("Başarılı!");
      },
      error: function()
      {
        alert("Başarısız!");
      }
    });
  }
}